package com.lanmon.util;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class CommonUtil {
	private CommonUtil() {
	}
	
	/**
	 * 将相同类型对象实现按属性拷贝值
	 * @param from 存储即将被拷贝的数据
	 * @param to 目标对象
	 */
	@SuppressWarnings("unchecked")
	public static <T> void populate(T from, T to) {
		if (from == null || to == null) {
			return;
		}
		Class<T> clz = (Class<T>) from.getClass();
		Field[] fields = clz.getDeclaredFields();
		for (Field field : fields) {
			String fieldName = field.getName();
			try {
				PropertyDescriptor pd = new PropertyDescriptor(fieldName, clz);
				Method get = pd.getReadMethod();
				Object object = get.invoke(from);
				Method set = pd.getWriteMethod();
				set.invoke(to, object);
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}
}
